package cn.xlbweb.cli.service.impl;

import cn.xlbweb.cli.mapper.PermissionMapper;
import cn.xlbweb.cli.mapper.RolePermissionMapper;
import cn.xlbweb.cli.mapper.UserRoleMapper;
import cn.xlbweb.cli.model.*;
import cn.xlbweb.cli.common.ServerResponse;
import cn.xlbweb.cli.common.TableResponse;
import cn.xlbweb.cli.pojo.dto.ListPermissionDTO;
import cn.xlbweb.cli.pojo.vo.ListPermissionNameVO;
import cn.xlbweb.cli.service.IPermissionService;
import cn.xlbweb.cli.util.CliUtils;
import cn.xlbweb.cli.pojo.vo.ListPermissionVO;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: bobi
 * @date: 2019-09-16 23:15
 * @description:
 */
@Service
@Slf4j
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public List<String> listPermissionUri(Integer userId) {
        if (userId != null) {
            // 根据userId查询该用户的所有角色
            UserRoleExample userRoleExample = new UserRoleExample();
            userRoleExample.createCriteria().andUserIdEqualTo(userId);
            List<UserRole> userRoleList = userRoleMapper.selectByExample(userRoleExample);
            // 根据roleId查询该角色的所有权限
            List<Integer> permissionIdList = new ArrayList<>();
            for (UserRole userRole : userRoleList) {
                RolePermissionExample rolePermissionExample = new RolePermissionExample();
                rolePermissionExample.createCriteria().andRoleIdEqualTo(userRole.getRoleId());
                List<RolePermission> rolePermissionList = rolePermissionMapper.selectByExample(rolePermissionExample);
                for (RolePermission rolePermission : rolePermissionList) {
                    permissionIdList.add(rolePermission.getPermissionId());
                }
            }
            // 根据permissionId查询所有的权限URI
            List<String> uriList = new ArrayList<>();
            for (Integer permissionId : permissionIdList) {
                Permission permission = permissionMapper.selectByPrimaryKey(permissionId);
                uriList.add(permission.getUri());
            }
            return uriList;
        }
        // 超级管理员 查询出所有权限
        List<String> uriList = new ArrayList<>();
        List<Permission> permissionList = permissionMapper.selectByExample(null);
        for (Permission permission : permissionList) {
            uriList.add(permission.getUri());
        }
        return uriList;
    }

    @Override
    public TableResponse listPermission(ListPermissionDTO listPermissionDTO) {
        log.info("listPermission() start...");
        // 构建查询条件
        PermissionExample permissionExample = new PermissionExample();
        if (StringUtils.isNotBlank(listPermissionDTO.getName())) {
            permissionExample.createCriteria().andNameLike("%" + listPermissionDTO.getName() + "%");
        }
        List<Permission> permissionList = permissionMapper.selectByExample(permissionExample);
        PageInfo<Permission> permissionPageInfo = new PageInfo<>(permissionList);

        // 构建Vo
        List<ListPermissionVO> listPermissionsVOList = CliUtils.getPermissionTree(permissionList, 0);
        log.info("listPermission() start...");
        return TableResponse.success(permissionPageInfo.getTotal(), listPermissionsVOList);
    }

    @Override
    public ServerResponse insertPermission(Permission permission) {
        // 判断权限名是否已经存在
        if (getPermissionByName(permission.getName()) != null) {
            return ServerResponse.error("权限名已存在");
        }
        // 插入权限
        int count = permissionMapper.insertSelective(permission);
        if (count > 0) {
            return ServerResponse.success("添加成功");
        }
        return ServerResponse.error("插入失败");
    }

    @Override
    public ServerResponse listPermissionName() {
        List<Permission> permissionList = permissionMapper.selectByExample(null);
        List<ListPermissionNameVO> voList = new ArrayList<>();
        permissionList.forEach(permission -> {
            ListPermissionNameVO vo = new ListPermissionNameVO();
            vo.setId(permission.getId());
            vo.setLabel(permission.getName());
            voList.add(vo);
        });
        // 根目录
        ListPermissionNameVO vo = new ListPermissionNameVO();
        vo.setId(0);
        vo.setLabel("根目录");
        voList.add(vo);
        return ServerResponse.success("查询成功", voList);
    }

    @Override
    public ServerResponse updatePermission(Permission permission) {
        // 判断权限名是否已经存在
        Permission dbPermission = permissionMapper.selectByPrimaryKey(permission.getId());
        if (!StringUtils.equals(permission.getName(), dbPermission.getName()) && getPermissionByName(permission.getName()) != null) {
            return ServerResponse.error("权限名已存在");
        }
        // 更新权限
        int count = permissionMapper.updateByPrimaryKeySelective(permission);
        if (count > 0) {
            return ServerResponse.success("更新成功");
        }
        return ServerResponse.error("更新失败");
    }

    @Override
    public ServerResponse deletePermission(String ids) {
        // 构建删除条件
        PermissionExample permissionExample = new PermissionExample();
        permissionExample.createCriteria().andIdIn(CliUtils.getIdList(ids));
        // 删除
        int count = permissionMapper.deleteByExample(permissionExample);
        if (count > 0) {
            return ServerResponse.success("删除成功");
        }
        return ServerResponse.error("删除失败");
    }

    private Permission getPermissionByName(String name) {
        PermissionExample permissionExample = new PermissionExample();
        permissionExample.createCriteria().andNameEqualTo(name);
        List<Permission> permissionList = permissionMapper.selectByExample(permissionExample);
        if (permissionList != null && !permissionList.isEmpty()) {
            return permissionList.get(0);
        }
        return null;
    }
}
